//
//  YDDataFormatManager.swift
//  YDPerfectServer
//
//  Created by rowena on 2019/7/31.
//

import PerfectHTTP
import Foundation

class YDDataFormatManager {

    //MARK: 通用响应格式
    static func baseResponseBodyJSONData(code: Int, message: String, data: Any!) -> String {
        
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let time = dateFormatter.string(from: date)
        
        var result = Dictionary<String, Any>()
        result.updateValue(code, forKey: "code")
        result.updateValue(message, forKey: "message")
        result.updateValue(time, forKey: "time")
        if (data != nil) {
            result.updateValue(data!, forKey: "data")
        } else {
            result.updateValue("", forKey: "data")
        }
        guard let jsonString = try? result.jsonEncodedString() else {
            return ""
        }
        return jsonString
    }
    
    static func valueForKey(request:HTTPRequest, key:String) -> String? {
        if request.method == .get {
            let params = request.queryParams
            for (k,v) in params {
                if k == key {
                    return v
                }
            }
        } else if request.method == .post {
            let params = request.params()
            for (k,v) in params {
                if k == key {
                    return v
                }
            }
        }
        return nil
    }
    
    /**
     * 把网络请求的Request参数转换为字典
     */
    static func dictForRequest(request:HTTPRequest) -> [String: Any] {
        
        var dict: [String: Any] = [String: Any]()
        
        if request.method == .get {
            let params = request.queryParams
            for (key, value) in params {
                dict.updateValue(value, forKey: key)
            }
        } else if request.method == .post {
            let params = request.params()
            for (key, value) in params {
                dict.updateValue(value, forKey: key)
            }
        }
        return dict
    }
    
}
